package wsepForum.ui.jaxcent.states;

import java.util.Map;
import java.util.Vector;

import jaxcent.HtmlElement;
import jaxcent.HtmlInputText;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;
import wsepForum.common.elements.Message;
import wsepForum.common.elements.SearchResult;
import wsepForum.ui.jaxcent.IXContext;

public class XSearchQuery extends AXQuery {
	/*****************************
	 * MEMBERS                   *
	 *****************************/
	final static private int BY_DATE = 0;
	final static private int BY_USER = 1;
	final static private int BY_BODY = 2;
	private HtmlElement xFromDateField;
	private HtmlElement xToDateField;
	private HtmlElement xContentField;
	private HtmlInputText xContent;

	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public XSearchQuery(IXContext context)
	{
		super(context);
		dealWithTypeChange(BY_DATE);
	}


	/*****************************
	 * METHODS                   *
	 *****************************/
	/* (non-Javadoc)
	 * @see wsepForum.ui.jaxcent.states.AXQuery#construct()
	 */
	@Override
	protected void construct() {
		String title,extraFields,types;
		title = "Search";
		extraFields =
		"<dl style=\"display: none;\" id=\"xdate2\"><dt><label for=\"xdate2\">To Date:</label></dt>"+
		"<dd>Day <select tabindex=\"5\" id=\"xdate2day\">"+DAYS+"</select>"+
		"&nbsp;Month <select tabindex=\"6\" id=\"xdate2month\">"+MONTHS+"</select>"+
		"&nbsp;Year <select tabindex=\"7\" id=\"xdate2year\">"+YEARS+"</select></dd></dl>"+
		"<dl style=\"display: none;\" id=\"xcontentfield\"><dt><label for=\"xcontent\">Content:</label></dt>"+
		"<dd><input id=\"xcontent\" type=\"text\" tabindex=\"9\" name=\"xtopic\" id=\"xtopic\" size=\"50\" value=\"\" class=\"inputbox autowidth\" /></dd>"+
		"</dl>";
		types =
			"<option>by date range</option>" +
			"<option>by author user</option>" +
			"<option>by content</option>";
		construct(title,extraFields,types);
	}

	@Override
	protected void dealWithTypeChange(int index) {
		this.type = index;
		try {
			switch (this.type) {
			case BY_DATE:
				this.xDesc.setInnerText("Search for messages in a specific date range");
				loadUsers(false);
				this.xFromDateField.show();
				this.xToDateField.show();
				this.xContentField.hide();
				break;
			case BY_USER:
				this.xDesc.setInnerText("Search for messages written by a specific user");
				loadUsers(true);
				this.xFromDateField.hide();
				this.xToDateField.hide();
				this.xContentField.hide();
				break;
			case BY_BODY:
				this.xDesc.setInnerText("Search for messages with a specific content");
				loadUsers(false);
				this.xFromDateField.hide();
				this.xToDateField.hide();
				this.xContentField.show();
				break;
			}
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("cannot manipulate page!\n"+e.getMessage());
		}
	}

	@Override
	protected void initContent() {
		super.initContent();
		JaxcentPage page = this.context.getPage();
		this.xFromDateField = new HtmlElement(page,"xdate");
		this.xToDateField = new HtmlElement(page,"xdate2");
		this.xContentField = new HtmlElement(page,"xcontentfield");
		this.xContent = new HtmlInputText(page,"xcontent");
	}

	@Override
	@SuppressWarnings("unchecked")
	protected void dealWithQuery(Map pageData) {
		try {
			Vector<SearchResult> results = null;
			switch(this.type) {
			case BY_DATE:
				results = this.context.getSession().getHandler().searchByDate(getDate(1,pageData), getDate(2,pageData));
				break;
			case BY_USER:
				results = this.context.getSession().getHandler().searchByAuthor(getUserName(pageData));
				break;
			case BY_BODY:
				results = this.context.getSession().getHandler().searchByContent(getContent(pageData));
				break;
			}
			showResult(results);
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("Encountered an error interacting with page's fields!\n"+e.getMessage());
			this.context.loadSection(0);
		} catch (Exception e) {
			this.context.getPage().showMessageDialog("Encountered an error during the search!\n"+e.getMessage());
			this.context.loadSection(0);
		}
	}

	@SuppressWarnings("unchecked")
	protected String getContent(Map pageData) throws Jaxception{
		String content = this.xContent.getValue();
		System.out.println(content);
		return content;
	}

	private void showResult(Vector<SearchResult> results) {
		try {
			StringBuffer messagesBuffer = new StringBuffer();
			int bgnum = 2;

			if (results.size()>0) {
				for (SearchResult m : results) {
					messagesBuffer.append(makeResultItem(bgnum,m));
					bgnum = ((bgnum==1)?2:1);
				}
			} else {
				messagesBuffer.append("no messages found..<br /><br />&nbsp;");
			}
			this.xResults.setInnerHTML("<hr /><h2>Result</h2><br />"+messagesBuffer);
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("cannot display result!\n"+e.getMessage());
		}
	}

	private String makeResultItem(int bgnum, SearchResult result) {
		Message message = result.getMessage();
		int id = message.getElementID();

		String score = String.valueOf((int)(result.getScore()*100)) + "%";

		String messageBody = message.getBody().replace("\n-------------\n", "<HR \\>");
		String messageAuthor = message.getUserName();
		if (messageAuthor==null)
			messageAuthor="guest";
		messageBody = messageBody.replace("\n", "<BR \\>");
		return
		"<div id=\"MSG"+id+"\" class=\"post bg"+bgnum+"\"><div class=\"inner\">"+
		"<span class=\"corners-top\"><span></span></span>"+
		"<div class=\"postbody\">" +
		"<h3 class=\"first\"><a href=\"#MSG"+id+"\">"+message.getHeadLine()+"</a></h3>"+
		"<p class=\"author\"><a><img src=\"/images/icon_post_target.gif\" width=\"11\" height=\"9\" alt=\"message\" title=\"message\" />" +
		"</a>by <strong><a>"+messageAuthor+"</a></strong> at "+message.getTimeStamp()+"</p>"+
		"<div class=\"content\">"+messageBody+"</div>"+
		"</div><dl class=\"postprofile\"><dt>"+
		"<p class=\"author\"><a><img src=\"/images/icon_bookmark.gif\" alt=\"score\" title=\"score\" />" +
		"</a>score: <strong>"+score+"</strong></p>"+
		"<img src=\"/images/avatar.png\" width=\"64\" height=\"64\" alt=\"User's avatar\" /><br />"+
		"<a>"+messageAuthor+"</a></dt></dl>"+
		"<div class=\"back2top\"><a href=\"#wrap\" class=\"top\" title=\"Back to top\">Back to top</a></div>"+
		"<span class=\"corners-bottom\"><span></span></span></div></div>"+
		"<hr class=\"divider\" />";
	}

}
